package com.loveyukari.service;


import com.loveyukari.dao.RoomGoldRankDao;
import com.loveyukari.model.RoomGoldRank;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoomGoldRankService {




    @Autowired
    private RoomGoldRankDao roomGoldRankDao;

    public void addOrUpdateList(JSONArray list){
        if (list != null && list.size()> 0){
            JSONObject one = list.optJSONObject(0);
            int groupId = roomGoldRankDao.selectLastGroup();
            List<RoomGoldRank> oldList = roomGoldRankDao.selectListByGroupId(groupId);
            if (oldList.isEmpty() || (oldList.get(0).getGold() > one.optInt("gold")/100)){
                roomGoldRankDao.insertGroup();
                groupId = roomGoldRankDao.selectLastGroup();
                for (int i=0;i<list.size();i++){
                    JSONObject json = list.optJSONObject(i);
                    this.addRoomGoldRank(json,groupId);
                }
            } else {
                this.updateList(list,oldList,groupId);
            }
        }
    }

    public void addRoomGoldRank(JSONObject json,int groupId){
        RoomGoldRank roomGoldRank = new RoomGoldRank();
        roomGoldRank.setRank(json.optInt("crk"));
        roomGoldRank.setUserId(json.optInt("uid"));
        roomGoldRank.setGold(json.optInt("gold")/100);
        roomGoldRank.setGroupId(groupId);
        roomGoldRankDao.insertRoomGoldRank(roomGoldRank);
    }

    public void updateList(JSONArray list,List<RoomGoldRank> roomGoldRankList,int groupId){
        for (int i=0;i<list.size();i++){
            if (i >= roomGoldRankList.size()){
                JSONObject json = list.optJSONObject(i);
                this.addRoomGoldRank(json,groupId);
            } else {
                JSONObject json = list.optJSONObject(i);
                RoomGoldRank roomGoldRank = roomGoldRankList.get(i);
                int uid = json.optInt("uid");
                int gold = json.optInt("gold") / 100;
                int rank = json.optInt("crk");
                if (roomGoldRank.getGold() < gold){
                    roomGoldRank.setGold(gold);
                    roomGoldRank.setUserId(uid);
                } else if (roomGoldRank.getGold() == gold && roomGoldRank.getUserId() != uid){
                    roomGoldRank.setUserId(uid);
                } else {
                    continue;
                }
                roomGoldRank.setRank(rank);
                roomGoldRankDao.updateRoomGoldRank(roomGoldRank);
            }

        }
    }

    public List<RoomGoldRank> getRoomGoldRankList(){
        return this.roomGoldRankDao.selectTmp();
    }
}
